<template>
    <div class="newCustomerCont">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="130">
        <Divider orientation="left" style=" font-weight: 600;">楼盘</Divider>
        <Row>
          <Col span="12">
            <FormItem label="选择楼盘：" prop="selectRealEstateVal">
              <Select v-model="formValidate.selectRealEstateVal" filterable @on-select="selectRealEstateValFun" style="width:100%" placeholder="请选择选择楼盘" >
                  <Option v-for="(item, index) in selectRealEstateList"  :value="item.buildingId" :key="index">{{item.provinceCame ? item.provinceCame + ' | ' : ''}}{{item.cityName ? item.cityName + ' | ' : ''}}{{item.areaName ? item.areaName + ' | ' : ''}}{{item.buildingAlias}}</Option>
                </Select>
            </FormItem>
          </Col>
        </Row>
        <Divider orientation="left" style=" font-weight: 600;">线上互动</Divider>
        <FormItem label="客户头像：">
          <Upload
              ref="upload"
              :show-upload-list="false"
              :data="uploadData"
              name="multipartFile"
              :headers="uploadHeaders"
              :on-success="handleSuccess"
              :format="['jpg','png']"
              :max-size="2048"
              type="drag"
              :on-exceeded-size="handleMaxSize"
              :on-format-error="handleFormatError"
              :action="uploadImageUrl"
              style="display: block; width:60px;">
                <div class="UploadImg">
                  <Avatar v-if="!formValidate.fileList" icon="ios-person" size="60" />
                  <img v-if="formValidate.fileList" :src="formValidate.fileList">
                  <strong>编辑</strong>
                </div>
            </Upload>
        </FormItem>
        <Row>
          <Col span="8">
            <FormItem label="客户昵称：" prop="customerNicknameVal">
              <Input v-model="formValidate.customerNicknameVal" placeholder="请输入客户昵称" style=" width: 100%;"></Input>
            </FormItem>
          </Col>
          <Col span="8" >
            <FormItem label="来源渠道：" prop="channelSource">
              <Select v-model="formValidate.channelSource" :label-in-value="true" @on-select="sourceChannelFun" filterable style="width:100%" placeholder="请选择来源渠道" >
                <Option v-for="(item,index) in sourceChannelList" :disabled="item.validate == 2" :value="item.channelId" :key="index">{{ item.channelName }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8" >
            <FormItem label="互动方式：" prop="interactionMode">
              <Select v-model="formValidate.interactionMode" filterable style="width:100%" placeholder="请选择互动方式" >
                <Option v-for="(item, index) in interactiveWayList" :disabled="item.validate == 2" :value="item.channelId+''" :key="index">{{ item.channelName }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="互动对数/时长：" prop="interactiveLogarithmicDuration">
              <Input v-model="formValidate.interactiveLogarithmicDuration" placeholder="例：3对/5分钟" style=" width: 100%;"></Input>
            </FormItem>
          </Col>
          <Col span="8" >
            <FormItem label="互动时间：" prop="interactionTimeVal">
              <DatePicker type="datetime" :options="interactionTimeValOptions" v-model="formValidate.interactionTimeVal" format="yyyy-MM-dd HH:mm" placeholder="请选择互动时间" style="width: 100%"></DatePicker>
            </FormItem>
          </Col>
          <Col span="8" >&nbsp;</Col>
          <Col span="24">
            <FormItem label="要点备注：" prop="keyNotesVal">
              <Input type="textarea" :rows="3" v-model="formValidate.keyNotesVal" placeholder="请选择要点备注" style=" width: 100%;"></Input>
            </FormItem>
          </Col>
        </Row>
        <Divider orientation="left" style=" font-weight: 600;">留资</Divider>
        <Row>
          <Col span="24">
            <FormItem label="是否留资：" prop="whetherRetainCapitalVal">
              <RadioGroup v-model="formValidate.whetherRetainCapitalVal">
                <Radio label="1">是</Radio>
                <Radio label="2" style=" margin-left: 30px;">否</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          </Row>
          <Row v-if="formValidate.whetherRetainCapitalVal == 1">
            <Col span="8">
              <FormItem label="留资号码：" prop="reservedNumberVal">
                <Input v-model="formValidate.reservedNumberVal" placeholder="请输入留资号码" style=" width: 100%;"></Input>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem label="客户姓名：" prop="customerNameVal">
                <Input v-model="formValidate.customerNameVal" placeholder="请输入客户姓名" style=" width: 100%;"></Input>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem label="性别：" >
                <Select v-model="formValidate.genderVal" filterable style="width:100%" placeholder="请选择性别" >
                  <Option v-for="(item, index) in genderList" :value="item.val" :key="index">{{ item.name }}</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem label="备用号码：" prop="alternateNumber">
                <Input v-model="formValidate.alternateNumber" placeholder="请输入备用号码,多个中间逗号分隔" style=" width: 100%;"></Input>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem label="微信号：" prop="weChatNumber">
                <Input v-model="formValidate.weChatNumber" placeholder="请输入微信号,多个中间逗号分隔" style=" width: 100%;"></Input>
              </FormItem>
            </Col>
          </Row>
        
        <Divider orientation="left" style=" font-weight: 600;">置业需求</Divider>
        <Row>
          <Col span="8">
            <FormItem label="置业目的：" >
              <Select v-model="formValidate.purposeHomeOwnershipVal" filterable style="width:100%" placeholder="请选择置业目的" >
                <Option v-for="(item, index) in purposeHomeOwnershipList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="置业阶段：" >
              <Select v-model="formValidate.homeOwnershipStage" filterable style="width:100%" placeholder="请选择置业阶段" >
                <Option v-for="(item, index) in homeOwnershipStageList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="意向区域：" >
              <Select v-model="formValidate.intentAreaVal" multiple filterable style="width:100%" placeholder="请选择意向区域" >
                <Option v-for="(item, index) in intentAreaList" :value="item.cityCode" :key="item.cityCode" :label="item.cityName"></Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="意向户型：" >
              <Select v-model="formValidate.intentionTypeVal" multiple filterable style="width:100%" placeholder="请选择意向户型" >
                <Option v-for="(item, index) in intentionTypeList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="首选户型：" >
              <Select v-model="formValidate.preferredApartmentVal" multiple filterable style="width:100%" placeholder="请选择首选户型" >
                <Option v-for="(item, index) in intentionTypeList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="意向业态：" >
              <Select v-model="formValidate.intentionFormatVal" multiple filterable style="width:100%" placeholder="请选择意向业态" >
                <Option v-for="(item, index) in intentionFormatList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="意向面积：" >
              <Row>
               <Select v-model="formValidate.intentArea" multiple filterable style="width:100%" placeholder="请选择意向面积" >
                 <Option v-for="(item, index) in areaList" :value="item.searchParamId" :key="index" >
                   {{item.paramValues.start == 0?`${item.paramValues.end}㎡以下`:item.paramValues.end == 999999999?`${item.paramValues.start}㎡以上`:`${item.paramValues.start}-${item.paramValues.end}㎡`}}
                </Option>
              </Select>
            </Row>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="对比区域：" >
              <Select v-model="formValidate.contrastAreaVal" multiple filterable style="width:100%" placeholder="请选择对比区域" >
                <Option v-for="(item, index) in intentAreaList" :value="item.cityCode" :key="item.cityCode" :label="item.cityName"></Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="24">
            <FormItem label="对比竞品：" prop="compareCompetingProducts">
              <Input type="textarea" :rows="2" v-model="formValidate.compareCompetingProducts" placeholder="请选择对比竞品" style=" width: 100%;"></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="首付预算：" >
              <Row>
                <Col span="10">
                  <FormItem prop="downPaymentBudgetMin">
                    <Input v-model="formValidate.downPaymentBudgetMin" type="number" placeholder="请输入首付" style=" width: 100%;"></Input>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="10">
                  <FormItem prop="downPaymentBudgetMax">
                    <Input v-model="formValidate.downPaymentBudgetMax" type="number" placeholder="请输入首付" style=" width: 100%;"></Input>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">万</Col>
                <div class="formError" v-show="formErrorDownPaymentState">右侧值必须大于左侧输入值</div>
              </Row>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="单价预算：" >
              <Row>
              <Select v-model="formValidate.unitPrice" filterable style="width:100%" placeholder="请选择单价预算" >
                  <Option v-for="(item, index) in priceList" :value="`${item.paramValues.start}-${item.paramValues.end}`" :key="index" >
                    {{item.paramValues.start == 0?`${item.paramValues.end}元/㎡以下`:item.paramValues.end == 999999999?`${item.paramValues.start}元/㎡以上`:`${item.paramValues.start}-${item.paramValues.end}元/㎡`}}
                  </Option>
              </Select>
              </Row>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="总价预算：" >
              <Row>
              <Select v-model="formValidate.totalPrice" filterable style="width:100%" placeholder="请选择总价预算" >
                <Option v-for="(item, index) in totalPriceList" :value="`${item.paramValues.start}-${item.paramValues.end}`" :key="index" >
                   {{item.paramValues.start == 0?`${item.paramValues.end}万元以下`:item.paramValues.end == 999999999?`${item.paramValues.start}万元以上`:`${item.paramValues.start}-${item.paramValues.end}万元`}}
                </Option>
              </Select>
              </Row>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="付款方式：" >
              <Select v-model="formValidate.paymentMethodVal" filterable style="width:100%" placeholder="请选择付款方式" >
                <Option v-for="(item, index) in paymentMethodList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <Row>
              <Col span="22">
                <FormItem label="付款比例：" prop="paymentRatioVal">
                  <Input v-model="formValidate.paymentRatioVal" placeholder="请输入付款比例" style=" width: 100%;"></Input>
                </FormItem>
              </Col>
              <Col span="2" style="text-align: center; lineHeight: 32px;">%</Col>
            </Row>
          </Col>
          <Col span="8">
            <FormItem label="认可点：" >
              <Select v-model="formValidate.recognitionPoint" multiple filterable style="width:100%" placeholder="请选择认可点" >
                <Option v-for="(item, index) in recognitionPointList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="抗性点：" >
              <Select v-model="formValidate.resistancePoint" multiple filterable style="width:100%" placeholder="请选择抗性点" >
                <Option v-for="(item, index) in recognitionPointList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="24">
            <FormItem label="要点备注：" prop="homeOwnershipNotes">
              <Input type="textarea" :rows="3" v-model="formValidate.homeOwnershipNotes" placeholder="请选择要点备注" style=" width: 100%;"></Input>
            </FormItem>
          </Col>
        </Row>
        <Divider orientation="left" style=" font-weight: 600;">客户画像</Divider>
        <Row>
          <Col span="8">
            <FormItem label="职业：" prop="professionVal">
              <Input v-model="formValidate.professionVal" placeholder="请输入职业" style=" width: 100%;"></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="估算年龄：" prop="estimatedAge">
              <Input v-model="formValidate.estimatedAge" :maxlength="3" placeholder="请输入估算年龄" style=" width: 100%;"></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="名下房产：" >
              <Select v-model="formValidate.propertyUnderName" filterable style="width:100%" placeholder="请选择名下房产" >
                <Option v-for="(item, index) in propertyUnderNameList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <FormItem label="工作区域：">
              <provinceCityArea type="workingArea" @provinceCityDistrictFun="provinceCityDistrictFun"></provinceCityArea>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="现居住区域：">
              <provinceCityArea type="currentLiving" @provinceCityDistrictFun="provinceCityDistrictFun"></provinceCityArea>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="现居住小区：" prop="currentResidentialArea">
              <Input v-model="formValidate.currentResidentialArea" placeholder="请输入现居住小区" style=" width: 100%;"></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="现居所来源：" >
              <Select v-model="formValidate.sourceCurrentResidence" filterable style="width:100%" placeholder="请选择现居所来源" >
                <Option v-for="(item, index) in sourceCurrentResidenceList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="现居所格局：" >
              <Select v-model="formValidate.currentResidencePattern" filterable style="width:100%" placeholder="请选择现居所格局" >
                <Option v-for="(item, index) in currentResidencePatternList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="家庭结构：" >
              <Select v-model="formValidate.familyStructure" filterable style="width:100%" placeholder="请选择家庭结构" >
                <Option v-for="(item, index) in familyStructureList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="个人年收入：" >
              <Row>
                <Col span="10" >
                  <FormItem prop="personalAnnualIncomeMin">
                    <Input v-model="formValidate.personalAnnualIncomeMin" type="number" placeholder="请输入" style=" width: 100%;"></Input>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="10">
                  <FormItem prop="personalAnnualIncometMax">
                    <Input v-model="formValidate.personalAnnualIncometMax" type="number" placeholder="请输入" style=" width: 100%;"></Input>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">万</Col>
                <div class="formError" v-show="formErrorPersonalState">右侧值必须大于左侧输入值</div>
              </Row>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="家庭年收入：" >
              <Row>
                <Col span="10">
                  <FormItem prop="familyIncomeMin">
                    <Input v-model="formValidate.familyIncomeMin" placeholder="请输入" type="number" style=" width: 100%;"></Input>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="10">
                  <FormItem prop="familyIncomeMax">
                    <Input v-model="formValidate.familyIncomeMax" placeholder="请输入" type="number" style=" width: 100%;"></Input>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">万</Col>
                <div class="formError" v-show="formErrorFamilyState">右侧值必须大于左侧输入值</div>
              </Row>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="是否限购：" >
              <Select v-model="formValidate.whetherToPurchase" filterable style="width:100%" placeholder="请选择是否限购" >
                <Option v-for="(item, index) in whetherToPurchaseList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="购房资格：" >
              <Select v-model="formValidate.purchaseQualification" filterable style="width:100%" placeholder="请选择购房资格" >
                <Option v-for="(item, index) in purchaseQualificationList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="贷款资格：" >
              <Select v-model="formValidate.loanEligibility" filterable style="width:100%" placeholder="请选择贷款资格" >
                <Option v-for="(item, index) in loanEligibilityList" :value="item.val" :key="index">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="16">
            <FormItem label="特殊描述：" >
              <Input v-model="formValidate.specialDscription" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入特殊描述"></Input>
            </FormItem>
          </Col>
        </Row>
        <div class="footer">
          <Button @click="handleReset('formValidate')" style="margin-left: 8px">取消</Button>
          <Button type="primary" @click="handleSubmit('formValidate')">保存</Button>
        </div>
      </Form>
      <!-- 当前登录人若是有，在该楼盘下录入过 -->
      <Modal width="400" v-model="recordedExistenceState" :mask-closable="false" :footerHide="true" :closable='false' class="recordedExistenceModel">
        <p>该客户已在您的名下</p>
        <div class="footer">
          <Button @click="IknowFun" style="margin-left: 8px">我知道了</Button>
          <Button type="primary" @click="viewCustomerDetailsFun">查看客户详情</Button>
        </div>
      </Modal>
      <!-- 若有客户进度到访以上的，则不可保存成功 -->
      <Modal width="400" v-model="customerVisitState" :mask-closable="false" :footerHide="true" :closable='false' class="customerVisitModel">
        <p style=" font-size: 18px;">客户已到访案场</p>
        <p>归属人：{{successInfo.belongPersonName}}({{successInfo.orgName}})</p>
        <p>楼盘：{{successInfo.buildingAlias}}</p>
        <div class="footer">
          <Button type="primary" @click="customerVisitOK">OK</Button>
        </div>
      </Modal>
    </div>
</template>
<script>
  import tool from "@/common/tool.js"
  import secret from "@/common/secret.js"
  import { userBuilding, aggChannelGroupList, customerUserAdd, cityBaselist } from "@/api/customerManagement.js";
  import provinceCityArea from './components/provinceCityArea'
  import {unloadImageAll} from "@/api/building"
  import { getSelectedAllList} from "@/api/cityConfig"
  export default {
    components: {
      provinceCityArea
    },
    data() {
      const alternateNumberValidator = (rule, value, callback) => {
        let ruleRE = /^[\d,]*$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入数字、逗号'));
          } else {
            if (value.indexOf(",") != -1) {
              let NumberBoolean = value.split(',').every(function (val,index,arr) {
                return val.length <= 15
              })
              if (NumberBoolean) {
                callback();
              } else {
                callback(new Error('每个逗号内的电话号码，限制15位'));
              }
            } else {
              if (value.length > 15) {
                callback(new Error('单个留资号码只能输入15位'));
              } else {
                callback();
              }
            }
          }
        }
      };
      const weChatNumberValidator = (rule, value, callback) => {
        let ruleRE = /^[\a-\z\A-\Z0-9\u4E00-\u9FA5\.\,\?\<\>\。\，\-\——\=\;\@\！\!\+\$\#\%\*\（\)\|\~\&\{\}\"\“\”\`\_]+$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入中英文、数字、特殊符号'));
          } else {
            if (value.indexOf(",") != -1) {
              let NumberBoolean = value.split(',').every(function (val,index,arr) {
                return val.length <= 15
              })
              if (NumberBoolean) {
                callback();
              } else {
                callback(new Error('每个逗号内的微信号，限制20位'));
              }
            } else {
              if (value.length > 15) {
                callback(new Error('单个微信号只能输入20位'));
              } else {
                callback();
              }
            }
          }
        }
      };
      const intentAreaMinValidator = (rule, value, callback) => {
        this.formErrorState = false;
        let ruleRE = /^[1-9]\d*$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入正整数'));
          } else if (value.length > 6) {
            callback(new Error('不可超过6位'));
          } else if (parseFloat(this.formValidate.intentAreaMin) >= parseFloat(this.formValidate.intentAreaMax)) {
            this.formErrorState = true
            callback(new Error(' '));
          } else {
            callback();
          }
        }
      }
      const downPaymentBudgetMinValidator = (rule, value, callback) => {
        this.formErrorDownPaymentState = false;
        let ruleRE = /^[1-9]\d*$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入正整数'));
          } else if (parseFloat(this.formValidate.downPaymentBudgetMin) >= parseFloat(this.formValidate.downPaymentBudgetMax)) {
            this.formErrorDownPaymentState = true
            callback(new Error(' '));
          } else {
            callback();
          }
        }
      }
      const downPaymentBudgetMaxValidator = (rule, value, callback) => {
        this.formErrorDownPaymentState = false;
        let ruleRE = /^[1-9]\d*$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入正整数'));
          } else if (parseFloat(this.formValidate.downPaymentBudgetMin) >= parseFloat(this.formValidate.downPaymentBudgetMax)) {
            this.formErrorDownPaymentState = true
            callback(new Error(' '));
          } else {
            callback();
          }
        }
      }
      const personalAnnualIncomeMinValidator = (rule, value, callback) => {
        this.formErrorPersonalState = false;
        let ruleRE = /^[1-9]\d*$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入正整数'));
          } else if (parseFloat(this.formValidate.personalAnnualIncomeMin) >= parseFloat(this.formValidate.personalAnnualIncometMax)) {
            this.formErrorPersonalState = true
            callback(new Error(' '));
          } else {
            callback();
          }
        }
      }
      const personalAnnualIncometMaxValidator = (rule, value, callback) => {
        this.formErrorPersonalState = false;
        let ruleRE = /^[1-9]\d*$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入正整数'));
          } else if (parseFloat(this.formValidate.personalAnnualIncomeMin) >= parseFloat(this.formValidate.personalAnnualIncometMax)) {
            this.formErrorPersonalState = true
            callback(new Error(' '));
          } else {
            callback();
          }
        }
      }
      const familyIncomeMinValidator = (rule, value, callback) => {
        this.formErrorFamilyState = false;
        let ruleRE = /^[1-9]\d*$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入正整数'));
          } else if (parseFloat(this.formValidate.familyIncomeMin) >= parseFloat(this.formValidate.familyIncomeMax)) {
            this.formErrorFamilyState = true
            callback(new Error(' '));
          } else {
            callback();
          }
        }
      }
      const familyIncomeMaxValidator = (rule, value, callback) => {
        this.formErrorFamilyState = false;
        let ruleRE = /^[1-9]\d*$/
        if (!value) {
          callback();
        } else {
          if (!ruleRE.test(value)) {
            callback(new Error('请输入正整数'));
          } else if (parseFloat(this.formValidate.familyIncomeMin) >= parseFloat(this.formValidate.familyIncomeMax)) {
            this.formErrorFamilyState = true
            callback(new Error(' '));
          } else {
            callback();
          }
        }
      }
      return {
        successInfo: '',
        uploadData: {
          appName: 'M-Web',
          appVersion: '1.2.2',
          title: new Date().getTime()
        },
        uploadHeaders: {'token': tool.getToken()},
        uploadImageUrl: unloadImageAll,
        interactionTimeValOptions: {
          disabledDate (date) {
            return date && date.valueOf() > Date.now();
          }
        },
        cityCode: '',
        formErrorState: false,
        formErrorDownPaymentState: false,
        formErrorUnitPriceState: false,
        formErrorTotalState: false,
        formErrorPersonalState: false,
        formErrorFamilyState: false,
        recordedExistenceState: false,
        customerVisitState: false,
        selectRealEstateList: [],
        sourceChannelList: [],
        interactiveWayList: [],
        genderList: [{name: '男', val: '1'}, {name: '女', val: '2'}],
        purposeHomeOwnershipList:[{name: '请选择', val: '-4'}, {name: '自住', val: '1'}, {name: '投资', val: '2'}, {name: '自住兼投资', val: '3'}],
        homeOwnershipStageList:[{name: '请选择', val: '-4'}, {name: '出发筹备', val: '1'}, {name: '看盘比盘', val: '2'}, {name: '选盘选房', val: '3'}],
        intentAreaList: [],
        intentionTypeList: [{name: '一室', val: '1'}, {name: '二室', val: '2'}, {name: '三室', val: '3'}, {name: '四室', val: '4'}, {name: '五室及以上', val: '5'}],
        intentionFormatList: [{name: '高层', val: '1'}, {name: '别墅', val: '2'}, {name: '多层', val: '3'}, {name: '公寓', val: '4'}, {name: '商业', val: '5'}],
        paymentMethodList: [{name: '请选择', val: '-4'}, {name: '一次性付款', val: '1'}, {name: '商业贷款', val: '2'}, {name: '公积金贷款', val: '3'}, {name: '组合贷款', val: '4'}, {name: '分期付款', val: '5'}],
        recognitionPointList: [{name: '区域发展潜力', val: '1'}, {name: '区域自然环境', val: '2'}, {name: '区域人文环境', val: '3'}, {name: '地铁', val: '4'}, {name: '学区', val: '5'}, {name: '周边商业配套', val: '6'}, {name: '周边医疗配套', val: '7'}, {name: '客户圈层', val: '8'}, {name: '发展商品牌', val: '8'}, {name: '楼盘品质', val: '10'}, {name: '物业管理品牌', val: '11'}, {name: '推荐房源满意度', val: '12'}, {name: '交付时间', val: '13'}],
        propertyUnderNameList: [{name: '请选择', val: '-4'}, {name: '无房产', val: '0'}, {name: '有1套', val: '1'}, {name: '有2套', val: '2'}, {name: '有3套', val: '3'}, {name: '有4套', val: '4'}, {name: '有5套', val: '5'}, {name: '有5套以上', val: '-1'}],
        sourceCurrentResidenceList: [{name: '请选择', val: '-4'}, {name: '自购', val: '1'}, {name: '租住', val: '2'}],
        currentResidencePatternList: [{name: '请选择', val: '-4'}, {name: '1室1卫', val: '1'}, {name: '2室1卫', val: '2'}, {name: '3室1卫', val: '3'}, {name: '3室2卫', val: '4'}, {name: '4室2卫及以上', val: '5'}],
        familyStructureList: [{name: '请选择', val: '-4'}, {name: '单身', val: '1'}, {name: '夫妻', val: '2'}, {name: '三口之家', val: '3'}, {name: '四口之家', val: '4'}, {name: '三代同堂', val: '5'}, {name: '其他', val: '6'}],
        whetherToPurchaseList: [{name: '请选择', val: '-4'}, {name: '是', val: '1'}, {name: '否', val: '2'}],
        purchaseQualificationList: [{name: '请选择', val: '-4'}, {name: '有', val: '1'}, {name: '无', val: '2'}],
        loanEligibilityList: [{name: '请选择', val: '-4'}, {name: '有', val: '1'}, {name: '无', val: '2'}],
        formValidate: {
          selectRealEstateVal: '',
          fileList: '',
          customerNicknameVal: '',
          interactionMode: '',
          interactiveLogarithmicDuration: '',
          interactionTimeVal: '',
          keyNotesVal: '',
          whetherRetainCapitalVal: '2',
          reservedNumberVal: '',
          customerNameVal: '',
          genderVal: '',
          alternateNumber: '',
          weChatNumber: '',
          purposeHomeOwnershipVal: '',
          homeOwnershipStage: '',
          intentAreaVal: [],
          intentionTypeVal: [],
          preferredApartmentVal: [],
          intentionFormatVal: [],
          intentAreaMin: '',
          intentAreaMax: '',
          intentArea:[],
          contrastAreaVal: [],
          compareCompetingProducts: '',
          downPaymentBudgetMin: '',
          downPaymentBudgetMax: '',
          unitPriceBudgetMin: '',
          unitPriceBudgetMax: '',
          totalPriceBudgetMin: '',
          totalPriceBudgetMax: '',
          paymentMethodVal: '',
          paymentRatioVal: '',
          recognitionPoint: [],
          resistancePoint: [],
          homeOwnershipNotes: '',
          professionVal: '',
          estimatedAge: '',
          propertyUnderName: '',
          currentResidentialArea: '',
          sourceCurrentResidence: '',
          currentResidencePattern: '',
          familyStructure: '',
          personalAnnualIncomeMin: '',
          personalAnnualIncometMax: '',
          familyIncomeMin: '',
          familyIncomeMax: '',
          whetherToPurchase: '',
          purchaseQualification: '',
          loanEligibility: '',
          workingAreaSSQ: [],
          currentLivingSSQ: [],
        },
        ruleValidate: {
          selectRealEstateVal: [
            { required: true, message: '请选择选择楼盘', trigger: 'change' }
          ],
          customerNicknameVal: [
            { required: true, message: '请输入客户昵称', trigger: 'blur' },
            { max: 10, message: '不可超过10个字符', trigger: 'blur' },
            { pattern: /^[\a-\z\A-\Z0-9\u4E00-\u9FA5\.\,\?\<\>\。\，\-\——\=\;\@\！\!\+\$\#\%\*\（\)\|\~\&\{\}\"\“\”\`\_]+$/, message: '请输入中英文、数字、特殊符号', trigger: 'blur' }
          ],
          interactiveLogarithmicDuration: [
            { required: true, message: '请输入互动对数/时长', trigger: 'blur' },
            { pattern: /^[0-9\u4E00-\u9FA5\/]+$/, message: '请输入中文、数字、/', trigger: 'blur' },
            { max: 10, message: '不可超过10个字符', trigger: 'blur' }
          ],
          channelSource: [
            { required: true, message: '请选择来源渠道', trigger: 'change' }
          ],
          interactionMode: [
            { required: true, message: '请选择互动方式', trigger: 'change' }
          ],
          interactionTimeVal: [
            { required: true, type: 'date', message: '请选择互动时间', trigger: 'change' }
          ],
          keyNotesVal: [
            { required: true, message: '请选择要点备注', trigger: 'blur' },
            { max: 500, message: '不可超过500个字符', trigger: 'blur' },
          ],
          whetherRetainCapitalVal: [
            { required: true, message: '请选择是否留资', trigger: 'change' }
          ],
          reservedNumberVal: [
            { required: true, message: '请输入留资号码', trigger: 'blur' },
            { max: 15, message: '不可超过15位', trigger: 'blur' },
            { pattern: /^[0-9]*$/, message: '请输入数字', trigger: 'blur' }
          ],
          customerNameVal: [
            { required: true, message: '请输入客户姓名', trigger: 'blur' },
            { max: 20, message: '不可超过20个字符', trigger: 'blur' },
            { pattern: /^[\u4e00-\u9fa5_a-zA-Z]+$/, message: '请输入中英文', trigger: 'blur' }
          ],
          alternateNumber: [
            { validator: alternateNumberValidator, trigger: 'blur' }
          ],
          weChatNumber: [
            { validator: weChatNumberValidator, trigger: 'blur' }
          ],
          downPaymentBudgetMin: [
            { validator: downPaymentBudgetMinValidator, trigger: 'blur' }
          ],
          downPaymentBudgetMax: [
            { validator: downPaymentBudgetMaxValidator, trigger: 'blur' }
          ],
          homeOwnershipNotes: [
            { max: 500, message: '不可超过500个字符', trigger: 'blur' },
          ],
          compareCompetingProducts: [
            { max: 50, message: '不可超过50个字符', trigger: 'blur' },
          ],
          paymentRatioVal: [
            { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
          ],
          professionVal: [
            { max: 10, message: '不可超过10个字符', trigger: 'blur' },
            { pattern: /^[\u4e00-\u9fa5_a-zA-Z]+$/, message: '请输入中英文', trigger: 'blur' }
          ],
          estimatedAge: [
            { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
          ],
          currentResidentialArea: [
            { max: 10, message: '不可超过10个字符', trigger: 'blur' },
            { pattern: /^[\a-\z\A-\Z0-9\u4E00-\u9FA5]+$/, message: '请输入中英文、数字', trigger: 'blur' }
          ],
          personalAnnualIncomeMin: [
            { validator: personalAnnualIncomeMinValidator, trigger: 'blur' }
          ],
          personalAnnualIncometMax: [
            { validator: personalAnnualIncometMaxValidator, trigger: 'blur' }
          ],
          familyIncomeMin: [
            { validator: familyIncomeMinValidator, trigger: 'blur' }
          ],
          familyIncomeMax: [
            { validator: familyIncomeMaxValidator, trigger: 'blur' }
          ],
        },
        areaList:[],
        priceList:[],
        totalPriceList:[]
      }
    },
    methods: {
      // 省市区选择处理
      provinceCityDistrictFun(val) {
        if (val.type == 'workingArea') {
          this.formValidate.workingAreaSSQ = val.selectVal
        } else if (val.type == 'currentLiving') {
          this.formValidate.currentLivingSSQ = val.selectVal
        }
      },
      // 来源渠道
      sourceChannelFun(val) {
        let l = this.sourceChannelList.find(item=>item.channelId == val.value)
        this.interactiveWayList = JSON.parse(JSON.stringify(l.passageway));
      },
      //选择楼盘
      selectRealEstateValFun(val) {
        this.selectRealEstateList.map((item) => {
          if(item.buildingId == val.value) {
            this.cityCode = item.cityCode
            this.areaCityList();
            this.sourceChannelListFun();
            this.getSelectedAll();
          }
        })
      },
      // 数据提交
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            let {unitPrice, totalPrice} = this.formValidate,unitPriceBudget=[],totalBudget=[];
            unitPrice && unitPriceBudget.push({start:unitPrice.split("-")[0],end:unitPrice.split("-")[1]})
            totalPrice && totalBudget.push({start:totalPrice.split("-")[0],end:totalPrice.split("-")[1]})
            let parms = {
              paymentRatio: this.formValidate.paymentRatioVal,
              buildingId: this.formValidate.selectRealEstateVal,
              headPortrait: this.formValidate.fileList,
              nickName: this.formValidate.customerNicknameVal,
              channelSource: this.formValidate.channelSource,
              interactionMode: this.formValidate.interactionMode,
              interactionCountTime: this.formValidate.interactiveLogarithmicDuration,
              interactionTime: this.formValidate.interactionTimeVal,
              interactionRemark: this.formValidate.keyNotesVal,
              intentionPurpose: this.formValidate.purposeHomeOwnershipVal == '-4' ? '' : this.formValidate.purposeHomeOwnershipVal,
              housePurchasingPhase: this.formValidate.homeOwnershipStage == '-4' ? '' : this.formValidate.homeOwnershipStage,
              intentionRegion: this.formValidate.intentAreaVal.join(","),
              intentionHouseType: this.formValidate.intentionTypeVal.join(","),
              firstChoiceHouseType: this.formValidate.preferredApartmentVal.join(","),
              intentionProduct: this.formValidate.intentionFormatVal.join(","),
              intentionArea: this.formValidate.intentArea.join(","),
              contrastRegion: this.formValidate.contrastAreaVal.join(","),
              contrastCompetition: this.formValidate.compareCompetingProducts,
              downPaymentBudget: JSON.stringify([{start: this.formValidate.downPaymentBudgetMin, end: this.formValidate.downPaymentBudgetMax}]),
              unitPriceBudget:JSON.stringify(unitPriceBudget),
              totalBudget:JSON.stringify(totalBudget),
              paymentType: this.formValidate.paymentMethodVal == '-4' ? '' : this.formValidate.paymentMethodVal,
              approvePoints: this.formValidate.recognitionPoint.join(","),
              resistancePoints: this.formValidate.resistancePoint.join(","),
              intentionRemark: this.formValidate.homeOwnershipNotes,
              profession: this.formValidate.professionVal,
              estimateAge: this.formValidate.estimatedAge,
              houseNum: this.formValidate.propertyUnderName == '-4' ? '' : this.formValidate.propertyUnderName,
              nowLiveHouse: this.formValidate.currentResidentialArea,
              nowLiveSource: this.formValidate.sourceCurrentResidence == '-4' ? '' : this.formValidate.sourceCurrentResidence,
              nowHouseType: this.formValidate.currentResidencePattern == '-4' ? '' : this.formValidate.currentResidencePattern,
              familyStructure: this.formValidate.familyStructure == '-4' ? '' : this.formValidate.familyStructure,
              customerIncomeMin: this.formValidate.personalAnnualIncomeMin,
              customerIncomeMax: this.formValidate.personalAnnualIncometMax,
              familyIncomeMin: this.formValidate.familyIncomeMin,
              familyIncomeMax: this.formValidate.familyIncomeMax,
              specialDscription: this.formValidate.specialDscription,
              astrict: this.formValidate.whetherToPurchase == '-4' ? '' : this.formValidate.whetherToPurchase,
              buyHouseQualification: this.formValidate.purchaseQualification == '-4' ? '' : this.formValidate.purchaseQualification,
              loansQualification: this.formValidate.loanEligibility == '-4' ? '' : this.formValidate.loanEligibility,
            }
            if (this.formValidate.whetherRetainCapitalVal == 1) {
              parms.customerDetail = this.formValidate.whetherRetainCapitalVal
              parms.customerPhone = this.formValidate.reservedNumberVal
              parms.customerName = this.formValidate.customerNameVal
              parms.gender = this.formValidate.genderVal
              parms.standbyPhone = this.formValidate.alternateNumber
              parms.wechat = this.formValidate.weChatNumber
            } else {
              parms.customerDetail = '2'
              parms.customerPhone = ''
              parms.customerName = ''
              parms.gender = ''
              parms.standbyPhone = ''
              parms.wechat = ''
            }
            if (this.formValidate.workingAreaSSQ.length == 3) {
              let workQu = []
              this.formValidate.workingAreaSSQ.map((item)=>{
                workQu.push(item.value)
              })
              parms.workingArea = workQu.join(",")
            } else {
              parms.workingArea = ''
            }
            if (this.formValidate.currentLivingSSQ.length == 3) {
              let workQu = []
              this.formValidate.currentLivingSSQ.map((item)=>{
                workQu.push(item.value)
              })
              parms.livingArea  = workQu.join(",")
            } else {
              parms.livingArea  = ''
            }
            customerUserAdd(parms).then(res=>{
              //("1:正常返回; 2:弹框1 ;3弹框2")
              this.successInfo = res
              if (res.type == 1) {
                this.$Message.success('新增客户成功!');
                this.$router.push({path:'/customerManagement_center/allCustomers/details', query:{customerId: res.customerId, userCustomerId: res.userCustomerId, buildingId: res.buildingId}});
              } else if(res.type == 2) {
                this.recordedExistenceState = true
              } else if(res.type == 3) {
                this.customerVisitState = true
              }
            }).catch(err=>{
              this.$Message.error(err)
            })
          }
        })
      },
      handleReset (name) {
        this.$router.go(-1);
      },
      // 图像
      handleMaxSize (file) {
        this.$Message.warning('单个图片不能超过2MB');
      },
      handleFormatError (file) {
        this.$Message.warning('图片格式只支持jpg,png格式！');
      },
      handleSuccess(res, file) {
        if (res.code == '200') {
          let dataJson = JSON.parse(secret.Decrypt(res.data));
          this.formValidate.fileList = dataJson.imageURL
        } else {
          console.log('上传出错');
        }
      },
      // 当前登录人若是有，在该楼盘下录入过
      IknowFun() {
        this.recordedExistenceState = false
        this.$router.go(-1);
      },
      viewCustomerDetailsFun() {
        this.$router.push({path:'/customerManagement_center/allCustomers/details', query:{customerId: this.successInfo.customerId,userCustomerId:this.successInfo.userCustomerId ,buildingId: this.successInfo.buildingId}});
      },
      // 若有客户进度到访以上的，则不可保存成功
      customerVisitOK() {
        this.customerVisitState = false
      },
      // 获取渠道配置列表
      sourceChannelListFun(channelName) {
        let parms = {
          cityCode: this.cityCode
        }
        if(channelName) {
          parms.channelName = channelName
        }
        aggChannelGroupList(parms).then(res=>{
          this.sourceChannelList = res && res.list && res.list[0]?res.list[0].list:[];
        }).catch(err=>{
          this.$Message.error(err)
        })
      },
      // 获取所有行政区域
      areaCityList() {
        cityBaselist({
          level: 4,
          parentCode: this.cityCode
        }).then(res=>{
          if (res && res.list) {
            this.intentAreaList = res.list
          } else {
            this.intentAreaList = []
          }
        }).catch(err=>{
          this.$Message.error(err)
        })
      },
      //获取 面积 单价 总价筛选条件
      getSelectedAll(){
        getSelectedAllList({cityCode: this.cityCode,platform: 3}).then(res=>{
          if (res) {
            this.priceList = res.averagePrice || []
            this.totalPriceList = res.totalPrice || []
            this.areaList = res.area || []
          }
        })
      },
      // 初始化数据
      initData() {
        // 人员拥有的楼盘列表
        let params = {
          page: 1,
          rows: 99
        }
        userBuilding(params).then(res=>{
          if (res && res.list) {
            this.formValidate.selectRealEstateVal = res.list[0]&&res.list[0].buildingId
            this.selectRealEstateList = res.list
            this.cityCode = res.list[0]&&res.list[0].cityCode
            this.sourceChannelListFun();
            this.areaCityList();
            this.getSelectedAll()
          } else {
            this.selectRealEstateList = []
          }
        }).catch(err=>{
          this.$Message.error(err)
        })
      }
    },
    computed: {

    },
    created() {
      // 初始化数据
      this.initData()
    },
    mounted() {

    },
    watch: {

    },
  }
</script>
<style lang="scss" scoped>
.formError{
  position: absolute;
  top: 100%;
  left: 0;
  line-height: 1;
  padding-top: 6px;
  color: #ed4014;
}
.recordedExistenceModel{
  p{
    font-size: 18px;
    text-align: center;
    margin: 10px 0 30px;
  }
  .footer{
    text-align: center;
    button{
      width: 120px;
      margin: 0 10px;
    }
  }
}
.customerVisitModel{
  p{
    margin-bottom: 10px;
  }
  .footer{
    padding-top: 20px;
    text-align: center;
    button{
      width: 120px;
      margin: 0 10px;
    }
  }
}
.newCustomerCont{
  width: 1100px;
  margin: 0 auto;
  padding-bottom: 80px;
  /deep/ .ivu-upload-drag{
    border: none;
  }
  .footer{
    text-align: center;
    button{
      width: 80px;
      margin: 0 10px;
    }
  }
  .UploadImg{
    width: 60px;
    height: 60px;
    border-radius: 50%;
    overflow: hidden;
    position: relative;
    img{
      width: 100%;
      height: 100%;
      display: block;
    }
    strong{
      position: absolute;
      left: 0;
      bottom: 0;
      display: block;
      width: 100%;
      height: 20px;
      line-height: 18px;
      color: #fff;
      font-size: 12px;
      background-color: rgba(0,0,0,0.2);
    }
  }
}
</style>
